﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ResourcePool
{
    class Resource : IDisposable
    {

        static private List<Resource> resourcePool = new List<Resource>();
        static public int countOfAllResources;
        private bool available;
        private object res;

        private Resource()
        {
            this.available = true;
            res = new object();
        }

        public object Res
        {
            get
            {
                return this.res;
            }
            set
            {
                this.res = value;
            }
        }

        public static int CountAvailable()
        {
            int count = 0;
            foreach (Resource res in resourcePool)
            {
                if (res.available)
                {
                    count++;
                }
            }
            return count;
        }

        static private bool IsThereAvailable()
        {
            foreach (Resource res in resourcePool)
            {
                if (res.available)
                {
                    return true;
                }
            }
            return false;
        }

        public static Resource Get()
        {
            if (!IsThereAvailable())
            {
                resourcePool.Add(new Resource());
                countOfAllResources++;
            }
            foreach (Resource resource in resourcePool)
            {
                if (resource.available)
                {
                    resource.available = false;
                    return resource;
                }
            }
            return default(Resource);
        }

        ~Resource()
        {
            this.Dispose();
        }

        public void Dispose()
        {
            this.available = true;
        }
    }
}
